
import { ref, reactive, computed, nextTick, watch, provide, onMounted } from 'vue'
import hook from './tools'

export default function (params) {
    const { currentIndex, steps, popoverVisible, whiteScreenDuration, visible, padding, block } = params
    const { scrollToCenter, scrollInit } = hook({ whiteScreenDuration, block })

    const MAX = computed(() => steps.value.length - 1)
    const MIN = 0
    let timer = null
    const viewStyle = reactive({
        width: '0px',
        height: '0px',
        left: '-999px',
        top: '0px',
    })

    // 设置延迟显示
    const delayShow = () => {
        timer && clearTimeout(timer)
        timer = setTimeout(() => {
            popoverVisible.value = true
        }, 300)
    }

    // 元素存在的索引
    const elIsExistIndex = ref(0)

    // 下一步  type: init 初始化 索引不加; isResize: 是否是窗口大小改变，如果是，则不添加规则
    const next = (type, isResize) => {
        popoverVisible.value = false
        if (type === 'init') {
            !isResize && setGlobalScroll('hidden')
        } else {
            currentIndex.value = (currentIndex.value + 1 > MAX.value ? MAX.value : currentIndex.value + 1)
        }
        nextTick(() => {
            // 获取下一个元素
            const el = steps.value?.[currentIndex.value]?.el || null

            // 如果下一步的元素不存在，则自动跳过这一步骤，切换到下下一步，以此类推，且防止无限循环
            if (!el && (currentIndex.value < MAX.value)) {
                next()
                return
            }

            // 记录当前元素存在的索引位置，为了防止出现连续的元素不存在的情况，当前popover展示错误的问题
            if (el) {
                elIsExistIndex.value = currentIndex.value
            }

            // 如果递归循环判断到最后的下一个元素不存在，则自动跳转到elIsExistIndex存在的索引位置
            if (!el && (currentIndex.value + 1 > MAX.value)) {
                currentIndex.value = elIsExistIndex.value
                delayShow()
                return
            }

            scrollToCenter(() => {
                delayShow()
                const { width, height, left, top } = el?.getBoundingClientRect()

                Object.assign(viewStyle, {
                    width: `${width + (padding * 2)}px`,
                    height: `${height + (padding * 2)}px`,
                    left: `${left - padding}px`,
                    top: `${top - padding}px`,
                })
            }, { el })
        })
    }

    // 上一步
    const prev = () => {
        popoverVisible.value = false
        currentIndex.value = (currentIndex.value - 1 < MIN ? MIN : currentIndex.value - 1)
        nextTick(() => {
            // 获取上一个元素
            const el = steps.value?.[currentIndex.value]?.el || null
            // 如果上一步的元素不存在，则自动跳过这一步骤，切换到上上一步，以此类推，且防止无限循环
            if (!el && currentIndex.value > MIN) {
                prev()
                return
            }

            if (el) {
                elIsExistIndex.value = currentIndex.value
            }

            if (!el && currentIndex.value - 1 < MIN) {
                currentIndex.value = elIsExistIndex.value
                delayShow()
                return
            }

            scrollToCenter(() => {
                delayShow()
                const { width, height, left, top } = el?.getBoundingClientRect()

                Object.assign(viewStyle, {
                    width: `${width + (padding * 2)}px`,
                    height: `${height + (padding * 2)}px`,
                    left: `${left - padding}px`,
                    top: `${top - padding}px`,
                })
            }, { el })
        })
    }

    let isAdded = false // 是否添加了全局禁止滚动
    // 设置全局禁止/取消全局禁止滚动 (所有除了 .v3-tour-container 下的元素，以外的所有元素禁止滚动) 
    const setGlobalScroll = (value) => {
        const STYLE_SHEETS = document.styleSheets[0]
        if (value === 'hidden') {
            isAdded = true
            STYLE_SHEETS.addRule(`*:not(.v3-tour-container *)`, 'overflow: hidden !important;');
        } else {
            if (isAdded) {
                const index = STYLE_SHEETS.cssRules.length - 1
                STYLE_SHEETS.removeRule(index)
                isAdded = false
            }
        }
    }

    // 更改popover位置函数
    const changePopoverPosition = () => {
        
    }

    provide('changePopoverPosition', changePopoverPosition)

    // 视口改变
    const resizeHandler = () => {
        next('init', 'resize')
    }

    const initFn = () => {
        scrollInit()
        currentIndex.value = 0
        elIsExistIndex.value = 0
        Object.assign(viewStyle, {
            width: '0px',
            height: '0px',
            left: '-999px',
            top: '0px',
        })
        setGlobalScroll('visible')
        timer && clearTimeout(timer)
        resizeHandler && window.removeEventListener('resize', resizeHandler)
        popoverVisible.value = false
    }

    // 结束导航 初始化所有状态
    const close = () => {
        initFn()
        visible.value = false
    }

    watch(() => visible.value, (val) => {
        if (val) {
            next('init')
            // 视口改变时更新位置
            window.addEventListener('resize', resizeHandler)
            // const observer = new IntersectionObserver(entries => {
            //     console.log('resize')
            // }, { threshold: 0 })
            // observer.observe(steps.value?.[currentIndex.value]?.el);
        } else {
            initFn()
        }
    })

    
    return {
        viewStyle,
        next,
        prev,
        close,
        setGlobalScroll
    }
}